package com.zh.stargraph2.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.stargraph2.core.dto.request.UserLoginReqDTO;
import com.zh.stargraph2.core.dto.respone.UserLoginResDTO;
import com.zh.stargraph2.core.mapper.UserMapper;
import com.zh.stargraph2.core.pojo.User;
import com.zh.stargraph2.core.service.UserService;
import com.zh.stargraph2.core.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserLoginResDTO loginByPassword(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        if (StrUtil.isEmpty(userLoginReqDTO.getUsername()) ||
                StrUtil.isEmpty(userLoginReqDTO.getPassword())) {
            throw new BadRequestException("账号或密码不能为空");
        }
        User user = lambdaQuery()
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()), (c) -> {
                    c.eq(User::getMobile, userLoginReqDTO.getUsername());
                })
                .or(StrUtil.isNotEmpty(userLoginReqDTO.getUsername()), (c) -> {
                    c.eq(User::getUsername, userLoginReqDTO.getUsername());
                })
                .one();
        if (user == null || !BCrypt.checkpw(userLoginReqDTO.getPassword(), user.getPassword())) {
            throw new BadRequestException("手机号或密码不匹配");
        }
        return generateLoginInfo(user);
    }

    private UserLoginResDTO generateLoginInfo(User user) {
        UserLoginResDTO userLoginResDTO = BeanUtil.toBean(user, UserLoginResDTO.class);
        if (StrUtil.isEmpty(userLoginResDTO.getName())) {
            userLoginResDTO.setName(user.getUsername());
        }
        if (StrUtil.isEmpty(userLoginResDTO.getName())) {
            userLoginResDTO.setName(user.getMobile());
        }
        userLoginResDTO.setToken(JWTUtils.createJWT(userLoginResDTO.getId(), userLoginResDTO.getName()));
        return userLoginResDTO;
    }
}
